import netsvc
#import time
from datetime import time, date, datetime
import time
from osv import osv, fields
from osv.orm import intersect
from tools.amount_to_text import amount_to_text

class kdvn_payment_from_client(osv.osv):
    _name = 'kdvn.payment.from.client'
    _description="KDVN Payment From Client"
    
    def fields_get(self, cr, uid, fields=None, context=None):
        res = super(kdvn_payment_from_client, self).fields_get(cr, uid, fields, context)
        new_field={'search_in_line_contract':
                                        {'widget':u'char', 
                                         'type':u'char', 
                                         'name':u'search_in_line_contract', 
                                         'select': u'1', 
                                         'string':u'Job No.', 
                                         'invisible':True, 
                                         'visible':False, 
                                         'size':128, 
                                         'sql':"(Select distinct kpfc.id from kdvn_payment_from_client kpfc left join kdvn_contract_client kcc on kpfc.contract_id = kcc.id left join sale_order so on kcc.id = so.contract_id left join kdvn_project kp on so.project_e_id = kp.id or so.project_e_id = kp.id where coalesce(so.contract_id, 0)<>0 and kp.name || ' ' || kp.code ilike chr(37) || '%s' || chr(37))"
                                         }
                   }
        res.update(new_field)
        return res
    
    def unlink(self, cr, uid, ids, context=None):
        if ids:
            payment_id = ", ".join(map(str, ids))
            for rop in self.read(cr, uid, ids, ['state']):
                if rop['state'] not in ('draft'):
                    raise osv.except_osv("KDERP Warning !", "Can't delete payment please check status")
        unlink_ids = ids
        return super(kdvn_payment_from_client, self).unlink(cr, uid, unlink_ids, context=context)
    
    def _invoice_no(self, cr, uid, date=None, context={}):
        res=''
        input_year=False
        #raise osv.except_osv("E", type(date))
        current_year = time.strftime('%Y-%m-%d')
        
        if date:
            input_year = date
        else:
            input_year = current_year
        #raise osv.except_osv("E", input_year)
        cr.execute("Select\
                        lpad((max(substring(current_code from 1 for padding)::integer)+1)::text, padding, '0') || prefix || to_char(select_year, suffix) as new_code\
                    from\
                        (Select\
                            case when number is null then lpad('0', padding, '0') || prefix || to_char(select_year, suffix) else number end as current_code, \
                            padding, \
                            suffix, \
                            prefix, select_year\
                        from \
                            ir_sequence isq\
                        left join\
                            (select '%s'::date as select_year) vwtemp_year on 1=1\
                        left join\
                            kdvn_payment_from_client kpfc on number ilike lpad('_', padding, '_') || prefix || to_char(select_year, suffix)\
                        where \
                            code='kderp_payment_from_client' and isq.active) vwcurrent_code\
                    group by\
                        padding, \
                        suffix, \
                        prefix, \
                        select_year" % (input_year))
        if cr.rowcount:
            res=cr.fetchone()[0]
    
        return res

    
    def _contract_cost(self, cr, uid, ids, name, args, context={}):
        #kcc_obj=self.pool.get('kdvn.contract.client')
        res={}
        for pfc in self.browse(cr, uid, ids):
            contract_amount=0
            if pfc.contract_id:
                for ctc_line in pfc.contract_id.currency_line:
                    if ctc_line.currency_id.code == pfc.currency_id.code:
                        contract_amount = (ctc_line.contracted_amount or 0)
            res[pfc.id]=contract_amount
#        for id in ids:
#            res[id]=res.get(id, 0.0)
        return res
    
    def _get_previous_progress_payment(self, cr, uid, ids, name, args, context):
        res = {}
        if ids:
            kpfc_ids = ", ".join(map(str, ids))
            cr.execute("""Select 
                            kpfc.id, 
                            coalesce((Select
                                sum(progress_amount) as previous_amount
                            from
                                kdvn_payment_from_client sub_kpfc
                            left join
                                kderp_contract_payment_term_line sub_kcptl on sub_kpfc.payment_term_line_id = sub_kcptl.id
                            where
                                sub_kpfc.currency_id = kpfc.currency_id and sub_kpfc.contract_id = kpfc.contract_id and sub_kcptl.sequence<kcptl.sequence and state not in ('draft', 'cancel')),0) as previous_progress_payment
                        from 
                            kdvn_payment_from_client kpfc
                        left join
                            kderp_contract_payment_term_line kcptl on payment_term_line_id = kcptl.id
                        where kpfc.id in (%s)
                        order by sequence""" % kpfc_ids)
            for id, pamount in cr.fetchall():
                res[id] = pamount
        return res
           
    def _kdvn_amount_all(self, cr, uid, ids, name, args, context={}):
        res = {}
        for x in self.browse(cr, uid, ids, context=context):
            if x.calc_baseon == 'special_re':
                calc_retention = 0
                sp_retention = x.retention or 0
            else:
                sp_retention= calc_retention = x.retention or 0
            
            rop_amount = (x.progress_amount or 0.0) - (x.with_holding_amount or 0.0) + (x.kdvn_amount_tax or 0.0) + (x.adv_payment or 0.0) + (x.others or 0.0) + sp_retention
            
            res[x.id] ={'kdvn_amount_total':(x.progress_amount or 0.0) - (x.with_holding_amount or 0.0) + (x.kdvn_amount_tax or 0.0) + (x.adv_payment or 0.0) + (x.others or 0.0) + calc_retention}
            res[x.id].update({'rop_amount':rop_amount})
            #if x.currency_id.code=='IDR':
            rec_curr = 'US Dollar'
            for rec_curr_obj in x.received_ids:
                rec_curr = rec_curr_obj.recv_cur.spell
            in_word = amount_to_text(x.received_total, 'en', rec_curr, True).title()
            basic_claim = amount_to_text((x.progress_amount or 0.0) + (x.adv_payment or 0.0) + (x.others or 0.0) + calc_retention,'en', x.currency_id.spell, True).title() 
            claim_in_word = amount_to_text((x.progress_amount or 0.0) + (x.kdvn_amount_tax or 0.0) + (x.adv_payment or 0.0) + (x.others or 0.0) + calc_retention,'en', x.currency_id.spell, True).title()
            claim_in_word_wh = amount_to_text((x.progress_amount or 0.0) - (x.with_holding_amount or 0.0) + (x.kdvn_amount_tax or 0.0) + (x.adv_payment or 0.0) + (x.others or 0.0) + calc_retention,'en', x.currency_id.spell, True).title()
            rop_amount_word = amount_to_text(rop_amount,'en', x.currency_id.spell, True).title()
            
            cr.execute("Select spell from kderp_currency where code='IDR'")
            Spell = cr.fetchone()[0]
            vat_amount_idr_in_word = amount_to_text((x.kdvn_amount_tax or 0.0)*x.exchange_rate, 'en', Spell, True).title() 
            
            res[x.id].update({'rop_amount_word':rop_amount_word.replace('Us Dollar', 'US Dollar')})
            res[x.id].update({'total_in_word':in_word.replace('Us Dollar', 'US Dollar')})
            res[x.id].update({'claim_in_word':claim_in_word.replace('Us Dollar', 'US Dollar')})
            res[x.id].update({'basic_claim_in_word':basic_claim.replace('Us Dollar', 'US Dollar')})
            res[x.id].update({'claim_in_word_wh':claim_in_word_wh.replace('Us Dollar', 'US Dollar')}),
            res[x.id].update({'vat_idr_in_word':vat_amount_idr_in_word.replace('Us Dollar', 'US Dollar')})
        
        return res
    
#     def _get_word(self, cr, uid, ids, name, args, context={}):
#         res = {}
#         for x in self.browse(cr, uid, ids, context=context):
#             res[x.id] ={'kdvn_amount_total':(x.progress_amount or 0.0) - (x.with_holding_amount or 0.0) + (x.kdvn_amount_tax or 0.0) + (x.adv_payment or 0.0) + (x.others or 0.0) + (x.retention or 0)}
#         return res
    
#     def _cal_in_usd(self, cr, uid, ids, name, args, context=None):
#         res = {}
#         if ids:
#             for quo in self.browse(cr, uid, ids):
#                 exrate = quo.cal_exrate or 0
#                 if exrate==0:
#                     res[quo.id] = {'submit_amount_in_usd':0.0, 'submit_vat_in_usd':0.0, 'submit_total_in_usd':0.0}
#                     res[quo.id].update({'e_break_amount_in_usd':0.0, 'e_break_distcount_in_usd':0.0, 'e_break_total_in_usd':0.0})
#                     res[quo.id].update({'m_break_amount_in_usd':0.0, 'm_break_distcount_in_usd':0.0, 'm_break_total_in_usd':0.0})
#                     res[quo.id].update({'approved_amount_in_usd':0.0, 'approved_vat_in_usd':0.0, 'approved_total_in_usd':0.0})
#                 else:
#                     res[quo.id] = {'submit_amount_in_usd':quo.amount/exrate, 'submit_vat_in_usd':quo.amount_tax/exrate, 'submit_total_in_usd':quo.amount_total/exrate}
#                     res[quo.id].update({'e_break_amount_in_usd':quo.q_amount_e/exrate, 'e_break_distcount_in_usd':quo.q_amount_e_discount/exrate, 'e_break_total_in_usd':quo.q_amount_total_e/exrate})
#                     res[quo.id].update({'m_break_amount_in_usd':quo.q_amount_m/exrate, 'm_break_distcount_in_usd':quo.q_amount_m_discount/exrate, 'm_break_total_in_usd':quo.q_amount_total_m/exrate})
#                     res[quo.id].update({'approved_amount_in_usd':quo.approved_amount/exrate, 'approved_vat_in_usd':quo.amount_tax_approved/exrate, 'approved_total_in_usd':quo.amount_total_approved/exrate})
#         return res
                         
    def _exchange_rate(self, cr, uid, ids, name, args, context={}):
        res={}
        if ids:
            pfc_ids = ", ".join(map(str, ids))
            cr.execute("""Select 
                            kpfc.id, 
                            coalesce(fncompute(currency_id, get_default_currency(),date, 'tax_office'),0)
                        from 
                            kdvn_payment_from_client kpfc where id in (%s)""" % pfc_ids)
            for id, rate in cr.fetchall():
                res[id]=rate            
        return res
    

    def _kdvn_get_received_all(self, cr, uid, ids, name, args, context={}):
        res = {}
        for kpfc in self.browse(cr, uid, ids):
            tmp_amount = 0.0
            for kdvn_received in kpfc.received_ids:
                tmp_amount = tmp_amount + (kdvn_received.recv_amount or 0.0)
            res[kpfc.id] = tmp_amount
        return res
    
    def _get_project_e_m_id(self, cr, uid, ids, name, args, context={}):
        res={}
        d1, d2 = self.pool.get('ir.rule').domain_get(cr, uid, 'kdvn.project')
        #raise osv.except_osv("E", d1)
        kp_ids = ", ".join(map(str, d2))
        if len(kp_ids)>0:
            #raise osv.except_osv("E", kp_ids)
            for id in ids:
                cr.execute("Select \
                                coalesce(vwprojectm.id, vwprojecte.id) as id, \
                                project_m_id as job_m_id, \
                                project_e_id as job_e_id\
                            from\
                                (Select\
                                    kpfc.id, \
                                    project_m_id\
                                from\
                                    kdvn_payment_from_client kpfc\
                                left join\
                                    kdvn_contract_client kcc on kpfc.contract_id = kcc.id\
                                left join\
                                    sale_order so on so.state<>'draft' and kcc.id = so.contract_id and coalesce(project_m_id, 0)>0\
                                where \
                                   kpfc.id=%s and project_m_id in (%s) limit 1) vwprojectm\
                            full join\
                                (Select\
                                    kpfc.id, \
                                    project_e_id\
                                from\
                                    kdvn_payment_from_client kpfc\
                                left join\
                                    kdvn_contract_client kcc on kpfc.contract_id = kcc.id\
                                left join\
                                    sale_order so on so.state<>'draft' and kcc.id = so.contract_id and coalesce(project_e_id, 0)>0\
                                where \
                                    kpfc.id=%s and project_e_id in (%s) limit 1) vwprojecte on vwprojectm.id = vwprojecte.id" % (id, kp_ids, id, kp_ids))
                tmp_dict = cr.dictfetchone()
                res[tmp_dict.pop('id')]=tmp_dict
        else:
            for id in ids:
                cr.execute("Select\
                            kpfc.id, \
                            job_m_id, \
                            job_e_id\
                        from\
                            kdvn_payment_from_client kpfc\
                        left join\
                            (Select \
                                vwprojectm.id, \
                                project_m_id as job_m_id, \
                                project_e_id as job_e_id\
                            from\
                                (Select\
                                    kpfc.id, \
                                    project_m_id\
                                from\
                                    kdvn_payment_from_client kpfc\
                                left join\
                                    kdvn_contract_client kcc on kpfc.contract_id = kcc.id\
                                left join\
                                    sale_order so on so.state<>'draft' and kcc.id = so.contract_id and coalesce(project_m_id, 0)>0\
                                where \
                                   kpfc.id=%s limit 1) vwprojectm\
                            full join\
                                (Select\
                                    kpfc.id, \
                                    project_e_id\
                                from\
                                    kdvn_payment_from_client kpfc\
                                left join\
                                    kdvn_contract_client kcc on kpfc.contract_id = kcc.id\
                                left join\
                                    sale_order so on so.state<>'draft' and kcc.id = so.contract_id and coalesce(project_e_id, 0)>0\
                                where \
                                    kpfc.id=%s limit 1) vwprojecte on vwprojectm.id = vwprojecte.id) vwtemp on kpfc.id = vwtemp.id where kpfc.id =(%s)" % (id, id, id))
                tmp_dict = cr.dictfetchone()
                res[tmp_dict.pop('id')]=tmp_dict
#            for job_e_id, job_m_id in cr.fetchall():           
#                res[id] = {'job_e_id':job_e_id, 'job_m_id':job_m_id}
            #raise osv.except_osv("E", res)
        return res
    
    def _get_tax_percents(self, cr, uid, context={}):
        selection = []
        cr.execute("Select name, tax_percent from kderp_tax_code where active=true order by tax_percent asc")
        for name, per in cr.fetchall():
            selection.append((per, name))
        return selection
   
#    def _get_quotations(self, cr, uid, ids, name, args, context={}):
#        res={}
#        for pfc in self.read(cr, uid, ids, ['contract_id']):
#            quos = ''
#            if pfc['contract_id']:
#                ctc_id = pfc['contract_id'][0]
#                cr.execute("Select name from sale_order where state not in ('draft', 'cancel') and id=%s" % ctc_id)
#                for n in cr.fetchall():
#                    if quos=='':
#                        quos=n
#                    else:
#                        quos=quos+";"+n
#            res[pfc.id] = quos
#        return res
    TAX_BASEON_SELECTION = (('all', 'All'),
                            ('special_re', 'Retention Later') #This case Customer automatic payment retention after one year, Official Receipt and Faktur Pajak included Retention, Request Of Payment exlcuded Retention                              
                            )
    _order = "number" 
    _rec_name = "number"
    _columns = {
            'number':fields.char('Number', size=16, select=1, states={'draft':[('readonly', False)]}, readonly=True),
            'date':fields.date('Date', states={'draft':[('readonly', False)]}, readonly=True),
            
            'received_ids': fields.one2many('kdvn.received', 'payment_id', 'Received Money', readonly=True, states={'open': [('readonly', False)]}),
            'previous_progress_payment':fields.function(_get_previous_progress_payment, type='float', readonly=True, method=True, string='Previous Progress Payment'),
            'printnums':fields.integer("Number of Print invoice"),
            
            'contract_id':fields.many2one('kdvn.contract.client', 'Contract', select=1, states={'draft':[('readonly', False)]}, readonly=True, required=True),
            'owner_id':fields.many2one('res.partner', 'Owner', select=1, states={'draft':[('readonly', False)]}, readonly=True),
            'client_id':fields.many2one('res.partner', 'Client', select=1, states={'draft':[('readonly', False)]}, readonly=True),
            'address_id':fields.many2one('res.partner.address', 'Address', select=1, states={'draft':[('readonly', False)]}, readonly=True),
            'invoice_address_id':fields.many2one('res.partner.address', 'Invoice Address', select=1, states={'draft':[('readonly', False)]}, readonly=True),
            'currency_id':fields.many2one('kderp.currency', 'Curr.', required=True, states={'draft':[('readonly', False)]}, readonly=True, context={'typeofrate':'tax_office'}),
            'payment_term_line_id':fields.many2one('kderp.contract.payment.term.line', 'Payment Term Line', required=True, states={'draft':[('readonly', False)]}, readonly=True),
            'contract_ref':fields.char('Contract Ref.', size=100),
    
            'attached_progress_sent':fields.boolean('Progress Sent'),
            'attached_progress_received':fields.boolean('Progress Received'),
                
            'state': fields.selection([
                ('draft', 'Draft'),
                ('open', 'Waiting for Payment'),
                ('paid', 'Done'),
                ('cancel', 'Cancel')
                ], 'State', select=True, readonly=True),
            'exchange_rate':fields.function(_exchange_rate, type='float', digits=(16, 2),method=True, string='Ex.Rate'),
            #'exchange_rate_usd':fields.function(_exchange_rate_usd, type='float', digits=(16, 2),method=True, string='Ref. Ex.Rate(USD)'),
            'adv_payment': fields.float('Adv.Payment', digits=(16, 2),states={'draft':[('readonly', False)]}, readonly=True),
            'retention': fields.float('Retention', digits=(16, 2),states={'draft':[('readonly', False)]}, readonly=True),
            'others': fields.float('Others', digits=(16, 2),states={'draft':[('readonly', False)]}, readonly=True),
            'contract_amount': fields.function(_contract_cost, digits=(16, 2),method=True, string='Contract Amt.', type='float'),
            
            'received_total':fields.function(_kdvn_get_received_all, method=True, digits=(16, 2),string='Received', type='float'),
            
            'kdvn_amount_total':fields.function(_kdvn_amount_all, string='Claim Amount', method=True, type='float', digits=(16, 2),multi='_cal_total', 
                                                  store={'kdvn.payment.from.client':(lambda self, cr, uid, ids, c={}: ids, None, 20)}),
                
            'rop_amount':fields.function(_kdvn_amount_all, string='R.O.P. Amount', method=True, type='float', digits=(16, 2),multi='_cal_total', 
                                                  store={'kdvn.payment.from.client':(lambda self, cr, uid, ids, c={}: ids, None, 20)}),
            'rop_amount_word':fields.function(_kdvn_amount_all, string="ROP in Word", method=True, type='char', size=255, multi='_cal_total', 
                                            store={'kdvn.payment.from.client':(lambda self, cr, uid, ids, c={}: ids, None, 20)}),
            
            'total_in_word':fields.function(_kdvn_amount_all, string="Total in Word", method=True, type='char', size=255, multi='_cal_total', 
                                            store={'kdvn.payment.from.client':(lambda self, cr, uid, ids, c={}: ids, None, 20)}),
            'claim_in_word':fields.function(_kdvn_amount_all, string="Total in Word", method=True, type='char', size=255, multi='_cal_total', 
                                            store={'kdvn.payment.from.client':(lambda self, cr, uid, ids, c={}: ids, None, 20)}),
            'basic_claim_in_word':fields.function(_kdvn_amount_all, string="Claim Basic in Word", method=True, type='char', size=255, multi='_cal_total', 
                                            store={'kdvn.payment.from.client':(lambda self, cr, uid, ids, c={}: ids, None, 20)}),
            'vat_idr_in_word':fields.function(_kdvn_amount_all, string="VAT in Word", method=True, type='char', size=255, multi='_cal_total', 
                                            store={'kdvn.payment.from.client':(lambda self, cr, uid, ids, c={}: ids, None, 20)}),
            'claim_in_word_wh':fields.function(_kdvn_amount_all, string="VAT in Word", method=True, type='char', size=255, multi='_cal_total', 
                                            store={'kdvn.payment.from.client':(lambda self, cr, uid, ids, c={}: ids, None, 20)}),
            'progress_amount':fields.float('Progress Amount', digits=(16, 2), states={'draft':[('readonly', False)]}, readonly=True),
            
            'calc_baseon':fields.selection(TAX_BASEON_SELECTION, 'Tax base on', states={'draft':[('readonly', False)]}, readonly=True,
                                          help='Retention later: This case Customer automatic payment retention after one year, Official Receipt and Faktur Pajak included Retention, Request Of Payment excluded Retention'),
            
            'itemofrequest':fields.char('Item of request', size=256, states={'draft':[('readonly', False)]}, readonly=True),
            'description':fields.text('Description', states={'cancel':[('readonly', True)]}, readonly=False),
            'taxes_percent':fields.selection(_get_tax_percents, "VAT (%)", states={'draft': [('readonly', False)]}, select=2, readonly=True),
            'kdvn_amount_tax':fields.float('Taxes', readonly=True, states={'draft': [('readonly', False)]}),
            
            'with_holding_taxes_percent':fields.selection(_get_tax_percents, "W.H. Taxes (%)", select=2, states={'draft': [('readonly', False)]}, readonly=True),
            'with_holding_amount':fields.float("W.H. Amt.", select=2, states={'draft': [('readonly', False)]}, readonly=True),
            
            'payment_details_ids':fields.one2many('kderp.payment.from.client.detail', 'payment_id', 'Payment Detail', ondelete='cascade', states={'draft': [('readonly', False)]}, readonly=True),
            'kderp_payment_vat_invoice_ids':fields.one2many('kderp.vat.invoice', 'payment_id', 'VAT Invoice(s)', states={'draft':[('readonly', False)]}, readonly=True),
            'special_case':fields.boolean('Special Case', states={'draft': [('readonly', False)]}, readonly=True),
            'manual_case':fields.boolean('Manual Case', states={'draft': [('readonly', False)]}, readonly=True)
            }
    _sql_constraints = [('pts_code_unique', 'unique (number)', 'The Code of the Payment must be unique !'),('payment_contract_payemnt_term_is_unique', 'unique (contract_id, payment_term_line_id, currency_id)', 'Payment for Contract and Paymen Term must be unique !')]
    _defaults = {  
        'state':lambda *x: 'draft', 
        'progress_amount':lambda *x:0.0, 
        'printnums':lambda *x:3,
        'calc_baseon': lambda *x: 'all',
        #'amount_e':lambda *x: 0.0, 
        ##amount_m':lambda *x: 0.0, 
        'kdvn_amount_tax':lambda *x:0.0, 
        'taxes_percent':lambda *x:10, 
        'adv_payment':lambda *x:0.0, 
        'retention':lambda *x:0.0, 
        'others':lambda *x:0.0
        }
    
    def action_cancel(self, cr, uid, ids, *args):
        self.write(cr, uid, ids, {'state':'cancel', 'move_id':False})
        self._log_event(cr, uid, ids, -1.0, 'Cancel Invoice')
        return True

    def action_cancel_draft(self, cr, uid, ids, *args):
        self.write(cr, uid, ids, {'state':'draft'})
        wf_service = netsvc.LocalService("workflow")
        for inv_id in ids:
            wf_service.trg_create(uid, 'kdvn.payment.from.client', inv_id, cr)
        return True
    
    def action_paid_cancel(self, cr, uid, ids, *args):
        self.write(cr, uid, ids, {'state':'cancel'})
        return True
    
    def copy(self, cr, uid, id, default=None, context={}):
        if default is None:
            default = {}
        default = default.copy()
        default.update({'state':'draft'})
        default['number']=''
        if 'date' not in default:
            default['date'] = False
        return super(kdvn_payment_from_client, self).copy(cr, uid, id, default, context)
   
    def _onchange_date(self, cr, uid, ids, oldnumber, date=None):
        if date:
            date=self.pool.get('kdvn.common.function').check_date(date)
        try:
            oldnumber=oldnumber.strip()
        except:
            oldnumber=oldnumber
        if oldnumber:
            new_number=oldnumber
        else:
            date = self.pool.get('kdvn.common.function').check_date(date)
            invoice_obj=self.pool.get('kdvn.payment.from.client')
            new_number=invoice_obj._invoice_no(cr, uid, date)#, {'type':check['type']})
        val={'number':new_number}        
        return {'value':val}
    
    def _onchange_amount_tax(self, cr, uid, ids, per=0.0, wh_per=0.0, progress_amount=0.0, kdvn_amount_tax=0.0, wh_amout=0.0, adv=0.0, retention=0.0, other=0.0, what_change=0, special_case=False, manual=False):
        #_onchange_amount_tax(tax_per, amount, advanced_amount, retention_amount, False, 1)
        #what_change=1 --> VAT AMOUNT, 2 --> WH Amount, 3--> Change Special Case
        if manual:
            #amount_total =  progress_amount + adv + retention + other - wh_amout  + kdvn_amount_tax'kdvn_amount_total':amount_total
            return {'value':{}}
        if special_case:
            subtoal_amount = progress_amount
        else:
            subtoal_amount = progress_amount +  adv + retention + other
        
        if not kdvn_amount_tax and what_change!=1:
            amount_tax=int(per)*(subtoal_amount)/100.0
        else:
            amount_tax = kdvn_amount_tax
            
        if not wh_amout and what_change!=2:
            wh_amout=int(wh_per)*(subtoal_amount)/100.0            
        else:
            wh_amout=wh_amout
                
        if what_change==1:
            if abs(kdvn_amount_tax - int(per)*(subtoal_amount)/100.0)<=1:
                amount_tax=kdvn_amount_tax            
            else:
                amount_tax=int(per)*(subtoal_amount)/100.0
                
        if what_change==2:
            if abs(wh_amout - int(wh_per)*(subtoal_amount)/100.0)<=1:
                wh_amout=wh_amout            
            else:
                wh_amout=int(wh_per)*(subtoal_amount)/100.0
                
        if what_change==3:
            amount_tax=int(per)*(subtoal_amount)/100.0
            wh_amout=int(wh_per)*(subtoal_amount)/100.0
            
        if special_case:
            amount_total= amount_tax + subtoal_amount - wh_amout  +  adv + retention + other
        else:
             amount_total= amount_tax + subtoal_amount - wh_amout
    
        val={'kdvn_amount_total':amount_total, 'kdvn_amount_tax':amount_tax, 'with_holding_amount':wh_amout}
        result={'value':val}        
        return result
    
    def _onchange_partner_id(self, cr, uid, ids, partner_id):
        invoice_addr_id = False
        address_id = False
        if partner_id:
            res = self.pool.get('res.partner').address_get(cr, uid, [partner_id], ['default', 'invoice'])
            invoice_addr_id = res['invoice']
            address_id = False
            if res['default']:
                address_id = res['default'] 
            if not invoice_addr_id and address_id:  
                invoice_addr_id =address_id
                
        result = {'value': {'invoice_address_id': invoice_addr_id, 
                            'address_id':address_id}}
        return result
    
    def _onchage_contract_id(self, cr, uid, ids, contract_id, partner_id=False):
        result={}
        if not contract_id:
            result=self._onchange_partner_id(cr, uid, ids, partner_id)
            result['value']['client_id']=partner_id
          #  result['value']['contract_currency_id']=False
        else:
            owner_id = False
            client_id = False
            address_id = False
            invoice_address_id = False
            contract_currency_id = False
            ctc_ref = False
            ctc_record=self.pool.get('kdvn.contract.client').read(cr, uid, [contract_id], ['contract_currency', 
                                                                                        'owner_id', 'client_id', 
                                                                                        'address_id', 'invoice_address_id', 'contract_ref'])
            if ctc_record:
                ctc_ref = ctc_record[0]['contract_ref']
                if ctc_record[0]['client_id']:
                    client_id=ctc_record[0]['client_id']
                if ctc_record[0]['owner_id']:
                    owner_id=ctc_record[0]['owner_id']
                if ctc_record[0]['address_id']:
                   address_id=ctc_record[0]['address_id']
                if ctc_record[0]['invoice_address_id']:
                    invoice_address_id=ctc_record[0]['invoice_address_id']
              
                if not invoice_address_id:
                    invoice_address_id = address_id
            result={'value':{'client_id':client_id, 'owner_id':owner_id, 
                            'address_id': address_id, 'invoice_address_id': invoice_address_id, 
                            'contract_ref':ctc_ref }}
        return result

kdvn_payment_from_client()

class kderp_payment_from_client_detail(osv.osv):
    _name = 'kderp.payment.from.client.detail'
    _description="KDVN Payment From Client Detail"
    
    def _get_job_contracted_amount(self, cr, uid, ids, name, args, context):
        res = {}
        for kpfcd in self.browse(cr, uid, ids):
            curr = False
            amt = 0 
            if kpfcd.payment_id.currency_id:
                curr = kpfcd.payment_id.currency_id.name
            for prj in kpfcd.payment_id.contract_id.project_estimated_ids:
                if prj.project_id.id==kpfcd.project_id.id:
                    if curr.upper()=="IDR":
                        amt = prj.idr
                    elif curr.upper()=="USD":
                        amt = prj.usd
                    elif curr.upper()=="EUR":
                        amt = prj.eur
                    elif curr.upper()=="JPY":
                        amt = prj.jpy
                    elif curr.upper()=="SGD":
                        amt = prj.sgd
            res[kpfcd.id] = amt
        return res
    
    _columns={
              'payment_id':fields.many2one('kdvn.payment.from.client', 'Payment', required=True, ondelete='restrict'),
              'project_id':fields.many2one('kdvn.project', 'Project', required=True),
              'amount':fields.float('Amount', required=True),
              
              'contracted_amount':fields.function(_get_job_contracted_amount, string='Contracted', type='float', method=True)              
              }
kderp_payment_from_client_detail()